<template>
  <a-modal v-model="show" width="50%" title="编辑" :centered="true" :footer="null" class="edit-modal">
    <a-spin :spinning="spinning" size="large">
      <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
        <a-form-item label="名称" has-feedback>
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    max: 15,
                    message: '请输入会员卡名，不超过15个字符,不可输入符号！',
                    whitespace: true,
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                  }
                ]
              }
            ]"
            name="name"
            placeholder="请输入"
            :max-length="15"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="说明" has-feedback>
          <a-textarea rows="6" placeholder="请输入" :max-length="1000" v-decorator="['content', { rules: [{ required: true, max: 1000, message: '请输入介绍，不超过1000个字符！' }] }]" />
        </a-form-item>
        <a-form-item label="适用方" has-feedback>
          <a-select
            v-decorator="['applicableParty', { rules: [{ required: true, message: '请选择适用方！' }] }]"
            placeholder="请选择"
            @change="handleSelectChange"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option :value="2">集团</a-select-option>
            <a-select-option :value="1">BOX</a-select-option>
          </a-select>
        </a-form-item>
        <template v-if="cardCtrol">
          <a-form-item label="适用品牌" has-feedback>
            <a-select
              v-decorator="['brandId', { rules: [{ required: true, message: '请选择适用品牌！' }] }]"
              placeholder="请选择"
              :getPopupContainer="triggerNode => triggerNode.parentNode"
              @change="changeBrand"
            >
              <a-select-option v-for="(item, index) in arcBrandsList" :key="index" :value="item.weid">{{ item.brandName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="适用卡等级" has-feedback>
            <a-select v-decorator="['cardLevel', { rules: [{ required: true, message: '请选择适用卡等级！' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
              <a-select-option v-for="(item, index) in cardList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <a-form-item label="有效期(天)" has-feedback>
          <a-input
            v-decorator="['days', { rules: [{ required: false, pattern: /^[1-9]\d*$/, message: '请输入有效期，且是正整数！', whitespace: true }] }]"
            name="name"
            placeholder=" 请输入"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="价格(元)" has-feedback>
          <a-input-number
            v-decorator="[
              'price',
              {
                rules: [
                  {
                    required: false,
                    pattern: /^([0-9][0-9]*)+(\.[0-9]{1,2})?$/,
                    message: '请输入价格,小数点后保留两位！',
                    whitespace: true
                  }
                ]
              }
            ]"
            name="name"
            :min="0"
            :step="0.01"
            placeholder="请输入"
            autocomplete="off"
          />
        </a-form-item>
        <div v-if="boxCtrol">
          <a-form-item label="会员卡类型" has-feedback>
            <a-select v-decorator="['memberType', { rules: [{ required: true, message: '请选择会员卡类型!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
              <a-select-option :value="1">
                订阅卡
              </a-select-option>
              <a-select-option :value="2">
                体验卡
              </a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <a-divider />
        <a-form-item :wrapperCol="{ span: 24 }" class="footer-btn">
          <a-button htmlType="submit" type="primary">提交</a-button>
          <a-button style="margin-left: 18px" @click="handleBack">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { goodsCreate, goodsDetail, brandCondition, cardTypeCondition } from '@/api/box/product'
import { queryDim } from '@/api/goods'
import pick from 'lodash.pick'
export default {
  data() {
    return {
      spinning: true,
      form: this.$form.createForm(this),
      loading: false,
      productId: null,
      memberCardId: null,
      memberCardTypeId: null,
      skuId: null,
      arcBrandsList: [],
      cardList: [],
      boxCtrol: false,
      cardCtrol: false,
      show: false,
      mdl: {}
    }
  },
  created() {
    // this.fetchPathId()
    this.fetchBrands()
  },
  mounted() {},
  activated() {
    // this.fetchPathId()
  },
  methods: {
    showModal(id) {
      this.fetchPathId(id)
      this.show = true
    },
    async fetchPathId(id) {
      this.productId = id
      if (id !== 'add') {
        let data = await this.fetchData(id)
        await this.fetchCardLevel(data.brandId)
        await this.initialForm(data)
      } else {
        this.boxCtrol = false
        this.cardCtrol = false
        this.form.resetFields()
        // this.form.setFieldsValue(pick(this.mdl, 'name', 'applicableParty', 'content', 'price', 'days'))
        this.spinning = false
      }
    },
    fetchBrands() {
      /* queryDim().then(res => {
        if (res.code === 0) {
          this.arcBrandsList = res.data.arcBrands
        } else {
          this.$message.warning(res.msg)
        }
      }) */
      brandCondition().then(res => {
        if (res.code == 0) {
          this.arcBrandsList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchData(id) {
      const data = {
        requestData: id
      }
      return goodsDetail(data)
        .then(res => {
          if (res.code === 0) {
            return res.data
          } else {
            this.spinning = false
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchData:' + err)
        })
    },
    initialForm(data) {
      data.price = data.price / 100
      this.form.getFieldsValue()
      this.form.setFieldsValue({
        name: data.name,
        applicableParty: data.applicableParty,
        content: data.content,
        price: data.price,
        days: data.days
      })
      this.memberCardId = data.memberCardId
      this.memberCardTypeId = data.memberCardTypeId
      this.skuId = data.skuId
      if (data.applicableParty == 1) {
        this.boxCtrol = true
        this.$nextTick(() => {
          this.form.setFieldsValue({
            memberType: data.memberType
          })
        })
      } else if (data.applicableParty == 2) {
        this.boxCtrol = false
        this.cardCtrol = true
        this.$nextTick(() => {
          this.form.setFieldsValue({
            brandId: data.brandId,
            cardLevel: data.cardLevel
          })
        })
      }
      // this.imageUrl = data.posterImg
      this.spinning = false
    },
    changeBrand(value) {
      this.form.setFieldsValue({
        cardLevel: ''
      })
      this.fetchCardLevel(value)
    },
    fetchCardLevel(id) {
      let params = {
        weid: id
      }
      return cardTypeCondition(params).then(res => {
        if (res.code == 0) {
          this.cardList = res.data
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const data = values
          delete data.upload
          const price = data.price
          data.price = parseInt(price * 100)
          if (data.applicableParty == 2) {
            delete data.price
            delete data.memberType
            data.levelId = this.cardList.filter(e => e.id == data.cardLevel)[0].cVipDalei
          }
          this.submitCreate(data)
        }
      })
    },
    submitCreate(d) {
      const data = {
        requestData: d
      }
      if (this.productId !== 'add') {
        data.requestData.id = this.productId
        data.requestData.memberCardId = this.memberCardId
        data.requestData.memberCardTypeId = this.memberCardTypeId
        data.requestData.skuId = this.skuId
      }
      goodsCreate(data)
        .then(res => {
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.show = false
            this.$emit('updateTable')
            // this.$router.push('/box/product/fictitious/list')
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    handleBack() {
      this.show = false
    },
    handleSelectChange(value) {
      if (value == 2) {
        // 集团
        this.cardCtrol = true
        this.boxCtrol = false
      } else if (value == 1) {
        this.boxCtrol = true
        this.cardCtrol = false
      }
    }
  }
}
</script>
<style lang="less" scoped>
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
.footer-btn {
  text-align: right;
  margin-bottom: 0px;
}
.edit-modal {
  /deep/ .ant-modal-body {
    padding-left: 0;
    padding-right: 0;
    padding-bottom: 10px;
  }
  .ant-divider-horizontal {
    margin: 10px 0;
  }
  .ant-row {
    padding: 0 24px;
  }
}
</style>

